import numpy as np
import matplotlib.pyplot as plt
# 输入的样本
x_data = [1,2.0,3.0,5,6,7,8,9,10,11,12]
y_data = [1,2.0,3.0,5,6,7,8,9,10,11,12]

# 定义模型
def forward(x):
    return x * w
# 定义损失函数
def loss(x,y):
    y_pred = forward(x)
    return (y_pred - y) * (y_pred - y)
#权重以及平均均方误差需要保存下来，因此先准备两个空列表
w_list = []
mse_list = []

#生成0.0 到 4.0 的序列，每0.1间隔一次
for w in np.arange(0.0,4.1,0.1):
    print('w=',w)
    l_sum = 0
    for x_val,y_val in zip(x_data,y_data):
        y_pred_val = forward(x_val)
        loss_val = loss(x_val,y_val)
        l_sum += loss_val
        print('\t',x_val,y_val,y_pred_val,loss_val)
    MSE = l_sum/3
    print('MSE=',MSE)#算出MSE
    w_list.append(w)
    mse_list.append(MSE)

#Drwa the graph
plt.plot(w_list,mse_list)
plt.ylabel('Loss')
plt.xlabel('w')
plt.show()